package com.sias.serviceclient.service;

import com.sias.model.model.entity.User;
import com.sias.model.model.enums.UserRoleEnum;
import com.sias.model.model.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

import static com.sias.common.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务
 *
 * @author <a href="https://github.com/sogra">程序员sogra</a>
 */
@FeignClient(name = "oj-user-service",path = "/api/user/inner")
public interface UserFeignClient {

  @GetMapping("/get/id")
  User getById(@RequestParam("userId") long userId);

  @PostMapping("/get/ids")
  List<User> listByIds(@RequestParam("userIds") Collection<Long> userIds);


  /**
   * 获取当前登录用户
   *
   * @param request
   * @return
   */
  default User getLoginUser(HttpServletRequest request) {
    Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
    User currentUser = (User) userObj;
    if (currentUser == null || currentUser.getId() == null) {
      return null;
    }
    return currentUser;
  }

  ;

  /**
   * 是否为管理员
   *
   * @param request
   * @return
   */
  default boolean isAdmin(HttpServletRequest request) {
    Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
    User user = (User) userObj;
    return isAdmin(user);
  }

  ;

  /**
   * 是否为管理员
   *
   * @param user
   * @return
   */
  default boolean isAdmin(User user) {
    return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
  }

  ;


  /**
   * 获取脱敏的用户信息
   *
   * @param user
   * @return
   */
  default UserVO getUserVO(User user) {
    if (user == null) {
      return null;
    }
    UserVO userVO = new UserVO();
    BeanUtils.copyProperties(user, userVO);
    return userVO;
  }

  ;

}
